#!/bin/sh
# chkconfig: 2345 10 90 
# description: Start and Stop redis  

PATH=/usr/local/bin:/sbin:/usr/bin:/bin 
export PATH 
REDISPORT={{ redis_port }} 
EXEC={{ redis_basedir }}/bin/redis-server
REDIS_CLI={{ redis_basedir }}/bin/redis-cli

PIDFILE={{ redis_basedir }}/redis.pid
CONF="{{ redis_basedir }}/conf/redis.conf" 
AUTH=$(grep requirepass $CONF |awk '{print $NF}')
IP=$(grep bind $CONF |awk '{print $2}')

case "$1" in  
    start)
        if [ -f $PIDFILE ];then
            if [ $(ps -ef |grep  `cat $PIDFILE` |grep -v grep|wc -l) -eq 0 ];then
                rm -rf $PIDFILE
                echo "Starting Redis server..."
                $EXEC $CONF 
            else
                echo "$PIDFILE exists, process is already running or crashed."
            fi
        else 
            echo "Starting Redis server..." 
            $EXEC $CONF  
        fi  
        if [ "$?"="0" ]  
        then  
            echo "Redis is running..." 
        fi  
        ;;

    stop)  
        if [ ! -f $PIDFILE ]  
        then  
            echo "$PIDFILE exists, process is not running." 
        else 
            PID=$(cat $PIDFILE)  
            echo "Stopping..." 
	    echo $PID | xargs kill
            sleep 2
            while [ -x $PIDFILE ]
            do
                echo "Waiting for Redis to shutdown..."
                sleep 1
            done
            echo "Redis stopped"
        fi
        ;;
		
	status)
        redis_pid=`pidof $EXEC`
        pid_count=`echo $redis_pid | wc -w`
	  
        if [ $pid_count -gt 0 ]; then
          echo "Redis running ($redis_pid)"
          exit 0
        else
          echo "Redis not running"
          exit 2
        fi
	  ;;
	
    restart|force-reload)  
        ${0} stop  
        ${0} start  
        ;;  
    *)  
        echo "Usage: /etc/init.d/redis {start|stop|restart|force-reload}" >&2 
        exit 1 
esac

